package com.itheima.homework04;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;

public class DownloadThread implements Runnable{
    // 创建集合存放ip地址
    Set<String> ips = new HashSet<>();

    //客户端socket对象
    private Socket socket;

    public DownloadThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {

            OutputStream os = socket.getOutputStream();

            //创建输入流对象
            FileInputStream fis = new FileInputStream("d:/test/p1.png");

            //循环读取文件数据
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = fis.read(buf)) != -1) {
                //向客户端写出图片数据
                os.write(buf,0,len);
            }
            //输出完所有文件数据后，要告知客户端结束
            socket.shutdownOutput();

            //获得客户端的ip地址
            String ip = socket.getInetAddress().getHostAddress();
            if (ips.add(ip)) {
                System.out.println("恭喜"+ip+"同学，下载成功！！ 当前下载的人数是："+ips.size());
            }
            //释放资源
            fis.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
